<?php

namespace App\Http\Controllers;

use App\Models\Diocese;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\ResourceCollection;

use function PHPSTORM_META\map;

class DioceseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $model = Diocese::has('province');
        // $model = Diocese::query();
        // $model->provinceName()->get();
        if (request()->input('name')) {
            $model->where('name', 'like', '%' . request()->input('name') . '%');
        }
        
        $ret = $model->paginate();
        $ret->load('province');
        // $ret.map(function($dio){
        //     $dio->province->name;
        // });
        // $find = Diocese::findOrFail(10);
        // dump($find->province_name);
        // foreach($ret as $r){
        //     // dump($r->provinceName->name);
        //     // $r->provinceName();
        //     // dump($r->province);
        //     $r->province->name;
        // }
        return new ResourceCollection($ret);
    }

    public function getlist(Request $request){
        $model = Diocese::query();
        $province_adcode = $request->input('province_adcode');
        if($province_adcode){
            $model->where('province_adcode',$province_adcode);
        }
        $list = $model->select('id','province_adcode', 'title')->get();
        return new ResourceCollection($list);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        //        dump($request->all());
        Diocese::create($request->all());
        return $this->created();
        //        $diocese->save();
        //        dump($create);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $attributes = $request->only([
            'name','title','province_adcode','cathedral_id'
        ]);
        $attributes['updated_at'] = now();
        Diocese::findOrFail($id)->update($attributes);
        return $this->noContent();
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        Diocese::findOrFail($id)->delete();
        return $this->noContent();
    }
}
